import { Dropdown, Layout, Menu, Modal, MenuProps,message, Space } from "antd";
import { UpOutlined, DownOutlined, PlusOutlined, EditOutlined, ExclamationCircleFilled, DeleteOutlined, EllipsisOutlined } from '@ant-design/icons';
import { useRef, useEffect, useMemo, useState } from "react";
import { useLocation, useNavigate, useParams  } from "react-router-dom";
import {
  useDispatchMenu, useStateMenuList,useStateUserInfo,
  useStateOpenMenuKey, useStateSelectMenuKey
} from "@/store/hooks";
import { MenuItem } from "@/types";
import MyIcon from '@/components/Icon'
import cloudDatabaseIcon from "@/assets/images/cloudDatabaseIcon-2x.png";
import Detail from "./detail";
import { getMenu ,delDoc,editDocContent,addMenu,addApp,getAppList} from "@/api";
import { setTreeData, getDefaultSelectMenuKey, getLocalSelectMenuKey } from "@/utils";
// import { selectedList } from "./data";
import DailogComponent from './components/Dailog'
function List() {
  const { Content, Sider } = Layout;
  const { SubMenu } = Menu;
  const userInfo = useStateUserInfo()
  const renderDropdown = (item: MenuItem) => {

    const items: MenuProps['items'] = [
      {
        key: '1',
        label: (
          <Space onClick={(e) => {
            e.stopPropagation(); 
            handleEditAdd(null,item.uuid); 
            }}>
            <PlusOutlined  /> 新建
          </Space>
          
        )
      },
      {
        key: '2',
        label: (
          <Space onClick={(e) => { 
            e.stopPropagation();
            handleEditAdd(item,item.parent_id); 
            }} >
            <EditOutlined /> 编辑
          </Space>
        )
      },
      {
        key: '3',
        label: (
          <Space onClick={(e) => { 
            e.stopPropagation();
            handleDelMenu(item); 
            }}>
            <DeleteOutlined  /> 删除
          </Space>
        )
      }
    ]

      return <Dropdown menu={{ items }}>
              <EllipsisOutlined />
            </Dropdown>
  }

  const renderMenu = (item: MenuItem) => {
    if (item[MENU_SHOW] === false) {
      return null;
    }

    if (!item.children) {
      return <Menu.Item key={item['uuid']} >
        {item[MENU_TITLE]}
        {
          userInfo&&userInfo.isDocAdmin ?
          (<span className="opt-btn-r">
          {renderDropdown(item)}
        </span>) : null
        }
      </Menu.Item>
    }
    return (
      <SubMenu
        key={item['uuid']}
        title={<span> {item[MENU_TITLE]}
           {
              userInfo&& userInfo.isDocAdmin ?
              (<span className="opt-btn-r">
                {renderDropdown(item)}
              </span>) :null
           }
          </span>
          }
      >
        {item.children.map(i => renderMenu(i))}
      </SubMenu>
    );
  };
  const menuList = useStateMenuList()
  const location = useLocation()
  const navigate = useNavigate();

  const { stateSetMenuList, stateSetSelectMenuKey, stateSetOpenMenuKey } = useDispatchMenu()
  // 菜单组折叠  
  const { stateSetOpenMenuKey: onOpenChange } = useDispatchMenu()
  // 菜单选项
  const menuComponent = useMemo(() => menuList.map(m => renderMenu(m)), [menuList]);
  const openKeys = useStateOpenMenuKey()
  const selectedKeys = useStateSelectMenuKey()
  // const items = selectedList || [];
  const [items,setItems] = useState<any>([]);
  // const [selectType, setSelectType] = useState<any>();
  const [rowItem, setRowItem] = useState<any>({});
  const [PidItem, setPidItem] = useState<any>('');
  const [flag, setFlag] = useState<boolean>(true);
  const [keyPath, setKeyPath] = useState<string[]>([]);
  const [docId, setDocId] = useState<string | number>('');
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const { menuId } = useParams()
  const [selectType, setSelectType] = useState<any>('');

  const handleMenuClick: MenuProps['onClick'] = e => {
    setFlag(true)
    navigate(`/cloud_doc/${e.key}`, { replace: true })
  };
    // 获取应用类别
    const getApp = () => {
      getAppList().then(res => {
        if(Array.isArray(res.dirs)){
          res.dirs.forEach(item => {
            item.icon = <MyIcon img={cloudDatabaseIcon}/>
          })
          setItems(res.dirs)
          if (!selectType) {
            setSelectType(res.dirs[0])
          }
        }
      })
    }
   useEffect(() => {
    getApp()
    items.forEach((item:any) => {
      if (item?.key == location.pathname.split('/')[2]) {
        setSelectType(item)
      }
    })
  }, [location])
  // 获取菜单list
  const getMenuList = () => {
      items.forEach((item:any) => {
      if (item?.key == location.pathname.split('/')[2]) {
        setSelectType(item)
      }
    })
    if (!selectType.key) return
    getMenu(selectType?.key).then((res) => {
      const formatList = setTreeData(res.docs.reverse())  || []
      if(Array.isArray(res.docs)){
        stateSetMenuList(formatList);
        if (Array.isArray(res.docs) && res.docs.length>0) {
          getLocalSelectMenuKey()
          if (!selectedKeys || selectedKeys.length == 0) {
            setDocId(formatList[0]['uuid'])
            setKeyPath([String(formatList[0][MENU_KEY])])
          } else {        
            let value = getDefaultSelectMenuKey(formatList, getLocalSelectMenuKey())[0];
            if(formatList.length>0){
              setDocId(selectedKeys[0])
              setKeyPath([selectedKeys[0]])
              setFlag(false)
            }
            if(formatList.length>0 && flag) {
              // console.log('value',value);
              // console.log('selectedKeys--1',selectedKeys)
              setDocId(formatList[0]['uuid'])
              setKeyPath([String(formatList[0][MENU_KEY])])
            }
          }
        }
      }
    });
  }

  useEffect(() => {
    if (stateSetMenuList && typeof stateSetMenuList === "function") { 
      getMenuList()
    }
  }, [ stateSetMenuList,selectType]);
  useEffect(() => {
    if (docId) {      
      stateSetSelectMenuKey([String(docId)])
    }
  }, [docId])

  const onHandleMenuClick: MenuProps['onClick'] = e => {
    setDocId(e.key)
    setKeyPath(e.keyPath)
    
  };
  const handleClick = (value: string | number) => {
    setDocId(value)
  }
  // 菜单编辑 新增
  const handleEditAdd = (value: any,pid:any) => {
    setRowItem(value)
    setPidItem(pid)
    setIsModalOpen(true)
  }
  //菜单删除
  const { confirm } = Modal;
  const handleDelMenu = (item: any) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleFilled />,
      content: `确认删除菜单 - ${item && item.label} ?`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        delDoc(item.uuid).then(res => {
          getMenuList()
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const onCancel = () => {
    setIsModalOpen(false)
  }
  // 提交
  const onSubmit = (type:any,value:any) => {
    const directory_key = selectType?.key
    if(!type){ 
      editDocContent(rowItem.uuid,{...value,directory_key}).then((res:any) => {
        message.success('修改成功')
        setIsModalOpen(false)
        getMenuList()
      }).catch(() => {})
    }else{
      if(value.isApp === 'yes') {
        addApp({label:value.label,key:value.key}).then((res:any) => {
          message.success('新增成功')
          setIsModalOpen(false)
          getApp()
        }).catch(() => {})
      }else{
        const Value:any  = {
          key:value.key,
          label:value.label,
          parent_id:value.parent_id,
        }
        addMenu({...Value,directory_key,content:'### 请编写内容'}).then((res:any) => {
          message.success('新增成功')
          setIsModalOpen(false)
          getMenuList()
        }).catch(() => {})
      }
    }
  }
  return (
    <div>
      {isModalOpen && (
        <DailogComponent onSubmit={onSubmit} parent_id={PidItem} isModalOpen={isModalOpen} initialValues={rowItem} onCancel={onCancel} />
      )}
      <Layout>
        <Sider className="sider" theme={"light"}>
          <div style={{display:'flex'}}>
          <Dropdown menu={{ items, onClick: handleMenuClick }}>
            <div className='type-select'>
              {selectType?.icon}
              <div className='select-label'>{selectType?.label}</div>
              <div>
                <UpOutlined />
                <DownOutlined />
              </div>
            </div>
          </Dropdown>
         {
          userInfo&&userInfo.isDocAdmin ?
          (<PlusOutlined className="add_Btn" onClick={() => { handleEditAdd(null,null) }} /> ):null
         }
          </div>
          <Menu
            mode={'inline'}
            triggerSubMenuAction="click"
            onOpenChange={onOpenChange}
            openKeys={openKeys}
            selectedKeys={selectedKeys}
            onClick={onHandleMenuClick}
          >
            {menuComponent}
          </Menu>
        </Sider>
        <Layout className="site-layout" id='detail-wrapper'>
          <Content className="detail-wrapper" >
            <Detail docId={docId} handleClick={handleClick} keyPath={keyPath} menuList={menuList} />
          </Content>
        </Layout>
      </Layout>
    </div>
  );
}

export default List;
